﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace Pibby.Core
{
	public class NotifyingCollection<T> : Collection<T>
	{
		#region Attributes

		private bool _bulkUpdating;

		#endregion

		#region Events

		public event EventHandler CollectionChanged;

		#endregion Events

		#region Properties

		public bool BulkUpdating
		{
			get
			{
				return this._bulkUpdating;
			}

			set
			{
				this._bulkUpdating = value;

				if (this._bulkUpdating)
				{
					this.PendingUpdate = false;
				}
				else 
				{
					if (this.PendingUpdate)
					{
						this.NotifySubscribers();
						this.PendingUpdate = false;
					}
				}
			}
		}

		private bool PendingUpdate
		{
			get;
			set;
		}

		#endregion Properties

		#region Overrides

		protected override void ClearItems()
		{
			base.ClearItems();

			this.NotifyChanged();
		}

		protected override void InsertItem(int index, T item)
		{
			base.InsertItem(index, item);

			this.NotifyChanged();
		}

		protected override void SetItem(int index, T item)
		{
			base.SetItem(index, item);

			this.NotifyChanged();
		}

		protected override void RemoveItem(int index)
		{
			base.RemoveItem(index);

			this.NotifyChanged();
		}

		#endregion Overrides

		#region Protected Methods

		protected void NotifyChanged()
		{
			this.PendingUpdate = true;

			if (!this.BulkUpdating)
			{
				this.NotifySubscribers();
				this.PendingUpdate = false;
			}

			
		}

		#endregion Protected Methods

		private void NotifySubscribers()
		{
			EventHandler changed = this.CollectionChanged;

			if (changed != null)
				changed(this, EventArgs.Empty);
		}

	}
}
